#include "../head.h"

// 针对特定class的内存池
class _Data
{
public:
	_Data() :data(0) {}
	_Data(double d):data(d){}
	
	union 
	{
		double data;
		_Data* pMemNext;
	};
    // 指向自由链表头的指针 
	static _Data* freelistHead;
    // 每个小块大小
	const static int BlcokCount= 20;
public:
	static void* operator new(size_t size)
	{
		if (size != sizeof(_Data))
			return ::operator new(size);

		_Data* obj = nullptr;
		if (freelistHead)
		{
			obj = freelistHead;
			freelistHead = freelistHead->pMemNext;
		}
		else
		{
            // ::operator new(malloc)申请 sizeof(_Data) * BlcokCount 大小做战备池
			freelistHead = static_cast<_Data*>(::operator new(sizeof(_Data) * BlcokCount));
            // 处理1到倒数第二个Block
			for (int i = 1; i < BlcokCount - 1; ++i)
			{
				freelistHead[i].pMemNext = &freelistHead[i + 1];
			}
            // 最后一个Block的下一个指针为空
			freelistHead[BlcokCount - 1].pMemNext = nullptr;
			obj = freelistHead;
			++freelistHead;
		}
		return obj;
	}
	static void operator delete(void* delNode,size_t size)
	{
        cout << "customize operator delete" << endl;
		if (delNode == nullptr)
			return;
		if (size != sizeof(_Data))
		{
			::operator delete(delNode);
			return;
		}	
		_Data* obj = static_cast<_Data*>(delNode);
		obj->pMemNext = freelistHead;
		freelistHead = obj;
	}
};
_Data* _Data::freelistHead = nullptr;
int main()
{
	_Data* p1 = new _Data;
	cout << hex << p1 << endl;
	_Data* p2 = new _Data;
	cout << hex << p2 << endl;
	_Data* p3 = new _Data;
	cout << hex << p3 << endl;
	delete p1;
	// _Data* p4 = new _Data;
	// cout << hex << p4 << endl;
    {
        cout << "vector test " << endl;
        // 该初始化方法含义是3个元素是相同地址的复制
        vector<_Data *> table;
        for(int j = 0; j < 5; ++j)
            table.emplace_back(new _Data);
        cout << "table size is " << table.size() << endl;
        for(int i = 0; i < table.size(); ++i)
            cout << table[i] << " ";
        cout << endl;
    }
	return 0;
}
